package com.thinkgem.jeesite.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.SysMenuMapper;
import com.thinkgem.jeesite.modules.sys.entity.SysMenu;
import com.thinkgem.jeesite.modules.sys.utils.SysCacheUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 14:08 2018/8/13
 * @Modified By:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> implements IService<SysMenu> {
    public SysMenu get(String id) {
        // TODO:先从缓存中获取

        // 缓存中获取不到的话，再去查询数据库
        SysMenu sysMenu = this.baseMapper.selectById(id);
        // TODO:将查询结果加入缓存

        return sysMenu;
    }

    public List<SysMenu> getAllOrdered() {
        QueryWrapper queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.orderByAsc(SysMenu.COL_SORT);
        return this.list(queryWrapper);
    }

    /**
     * 获取所有子菜单
     *
     * @param id
     * @return
     */
    public List<SysMenu> selectChildren(String id) {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<SysMenu>();
        }
        String param = "," + id + ",";
        QueryWrapper queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.like(SysMenu.COL_PARENT_IDS, param);
        queryWrapper.orderByAsc(SysMenu.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    public List<SysMenu> findByUserId(String userId) {
        return this.baseMapper.findByUserId(userId);
    }

    /**
     * 根据角色获取
     *
     * @param roleId
     * @return
     */
    public List<SysMenu> findByRoleId(String roleId) {
        return this.baseMapper.findByRoleId(roleId);
    }

    @Transactional( rollbackFor = Exception.class)
    public boolean saveMenu(SysMenu sysMenu) {
        if (StringUtils.isBlank(sysMenu.getId())) {
            return this.insertMenu(sysMenu);
        }
        return this.updateMenu(sysMenu);
    }

    @Transactional( rollbackFor = Exception.class)
    public boolean insertMenu(SysMenu sysMenu) {
        // 设置parentids的值
        SysMenu parentMenu = this.baseMapper.selectById(sysMenu.getParentId());
        sysMenu.setParentIds(parentMenu.getParentIds() + sysMenu.getParentId() + ",");

        // 保存
        this.baseMapper.insert(sysMenu);
        return true;
    }

    @Transactional( rollbackFor = Exception.class)
    public boolean updateMenu(SysMenu sysMenu) {
        // 获取修改前的parentIds，用于更新子节点的parentIds
        SysMenu oldSysMenu = this.get(sysMenu.getId());
        String oldParentIds = oldSysMenu.getParentIds();

        // 设置新的父节点串
        SysMenu parentMenu = this.baseMapper.selectById(sysMenu.getParentId());
        sysMenu.setParentIds(parentMenu.getParentIds() + sysMenu.getParentId() + ",");

        // 保存或更新实体
        this.baseMapper.updateById(sysMenu);

        // 更新子节点 parentIds
        List<SysMenu> subMenuList = this.selectChildren(sysMenu.getId());
        for (SysMenu subMenu : subMenuList) {
            subMenu.setParentIds(subMenu.getParentIds().replace(oldParentIds, sysMenu.getParentIds()));
            this.baseMapper.updateById(subMenu);
        }
        // 清除日志相关缓存
        SysCacheUtils.removeMenuPathMap();
        return true;
    }

    /**
     * 更新菜单排序
     *
     * @param sysMenu
     * @return
     */
    @Transactional( rollbackFor = Exception.class)
    public int updateSort(SysMenu sysMenu) {
        // 如果排序号没变，则直接返回
        SysMenu currentInfo = this.get(sysMenu.getId());
        if (sysMenu.getSort().equals(currentInfo.getSort())) {
            return 0;
        }

        int resultNum = this.baseMapper.updateSort(sysMenu);
        // 清除日志相关缓存
        SysCacheUtils.removeMenuPathMap();
        return resultNum;
    }

    /**
     * 删除菜单
     *
     * @param sysMenu
     * @return
     */
    @Transactional( rollbackFor = Exception.class)
    public boolean delete(SysMenu sysMenu) {
        // TODO：删除角色菜单的对应关系

        // TODO： 删除角色对应人员的session并强制退出

        // 删除本菜单
        this.baseMapper.deleteById(sysMenu);

        // 删除子菜单
        QueryWrapper subWrapper = new QueryWrapper<SysMenu>();
        subWrapper.select(SysMenu.COL_ID);
        subWrapper.like(SysMenu.COL_PARENT_IDS, "," + sysMenu.getId() + ",");
        List<SysMenu> subMenuList = this.baseMapper.selectList(subWrapper);
        if (CollectionUtils.isNotEmpty(subMenuList)) {
            List<String> subIds = new ArrayList<String>();
            for(SysMenu subMenu:subMenuList){
                subIds.add(subMenu.getId());
            }
            this.baseMapper.deleteBatchIds(subIds);
        }

        // 清除日志相关缓存
        SysCacheUtils.removeMenuPathMap();

        return true;
    }
}
